package com.hugang.juc.test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者消费者问题
 *
 * @author hg
 * @date 2020/9/1 16:36
 */
public class ProducterConsumerDemo {

    public static void main(String[] args) {
        //solveBySynchronized();
        //solveByReentrantLock();
        solveByBlockingQueue();
    }

    public static void solveByBlockingQueue() {
        ArrayBlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(1);
        MyResource myResource = new MyResource(blockingQueue);
        new Thread(() -> {
            myResource.prod();
        }, "prod").start();

        new Thread(() -> {
            myResource.consume();
        }, "cons").start();

        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myResource.stop();
        System.out.println("main over");
    }

    public static void solveByReentrantLock() {
        Resource2 resource = new Resource2();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.add();
            }
        }, "线程1").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resource.add();
            }
        }, "线程2").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resource.sub();
            }
        }, "线程3").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.sub();
            }
        }, "线程4").start();
    }

    public static void solveBySynchronized() {

        Resource resource = new Resource();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.add();
            }
        }, "线程1").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resource.add();
            }
        }, "线程2").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resource.sub();
            }
        }, "线程3").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.sub();
            }
        }, "线程4").start();
    }
}

class Resource {
    int num = 0;

    public synchronized void add() {
        while (num > 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + ": " + num + " ---> " + ++num);
        notifyAll();
    }

    public synchronized void sub() {
        while (num <= 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + ": " + num + " ---> " + --num);
        notifyAll();
    }
}

class Resource2 {
    int num = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void add() {
        lock.lock();
        try {
            while (num > 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ": " + num + " ---> " + ++num);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void sub() {
        lock.lock();
        try {
            while (num <= 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ": " + num + " ---> " + --num);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

class MyResource {

    private BlockingQueue<Integer> blockingQueue = null;
    //是否停止标志
    private volatile boolean flag = true;
    private AtomicInteger atomicInteger = new AtomicInteger();

    public MyResource(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void prod() {
        while (flag) {
            int curInteger = atomicInteger.incrementAndGet();
            try {
                blockingQueue.offer(curInteger, 1000, TimeUnit.MILLISECONDS);
                System.out.println(Thread.currentThread().getName() + "：生产 ---> " + curInteger + "，当前阻塞队列中的数量：" + blockingQueue.size());
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("调用停止方法，生产线程结束");
    }

    public void consume() {
        while (flag) {
            try {
                Integer poll = blockingQueue.poll(1000, TimeUnit.MILLISECONDS);
                System.out.println(Thread.currentThread().getName() + "：消费 ---> " + poll + "，当前阻塞队列中的数量：" + blockingQueue.size());
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("调用停止方法，消费线程结束");
    }

    public void stop() {
        this.flag = false;
    }
}
